﻿using Inovout.Data.Domain;
using Inovout.Runtime;
using Inovout.Web.Mvc;
using KuaJing.Customs.Domain;
using KuaJing.Customs.Service;
using KuaJing.Orders.Service;
using SharpSvn;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace KuaJing.Tasks.WebPages.Controllers
{
    public class DeclarationController : RepositoryController<Declaration>
    {
        public override ActionResult Index(QueryCriteria queryCriteria)
        {
            queryCriteria = QueryCriteriaBuilder
                .FilterFor(t => t.ContractNumber, FilterOperation.Like)
                     .FilterFor(t => t.DeclarationDate, FilterOperation.GtEq)
                .FilterFor(t => t.DeclarationDate, FilterOperation.LeEq)
                .FilterFor(t => t.Code, FilterOperation.Like)
                .FilterFor(t => t.ExportDate, FilterOperation.GtEq)
               .FilterFor(t => t.ExportDate, FilterOperation.LeEq)
                .OrderDescendingFor(t => t.CreatedTime)
                .Merge(queryCriteria).QueryCriteria;

            ViewBag.OrderService = GetService<OrderService>();
            return base.Index(queryCriteria);
        }

        public ActionResult SyncSvn()
        {
            var settings = GetService<IApplication>().Properties;
            try
            {
                SvnUpdateDeclaration(settings["svn_repository_order"], settings["svn_local_order"], e => e.Action == SvnNotifyAction.UpdateCompleted && e.FullPath.ToLower().Contains("出口情况一览表"), f => GetService<OrderService>().Import(f.First()));
                //SvnUpdateDeclaration(settings["svn_repository_declaration"], settings["svn_local_declaration"], e => e.Action == SvnNotifyAction.UpdateAdd && e.FullPath.ToLower().EndsWith("pdf"), f => GetService<DeclarationService>().Import(f));
            }
            catch (Exception ex)
            {
                return View("Error", (object)"无法连接Svn服务器，请稍候在公司局域网内重试！");
            }
            return RedirectToAction("Relation", "Order", new { ReturnUrl = ViewBag.ReturnUrl });
        }
        private void SvnUpdateDeclaration(string repository, string localPath,
            Func<SvnNotifyEventArgs, bool> filter, Action<IEnumerable<string>> import)
        {
            List<string> files = new List<string>();
            using (SvnClient client = new SvnClient())
            {
                //SvnInfoEventArgs serverInfo;
                //SvnInfoEventArgs clientInfo;
                SvnUriTarget target = new SvnUriTarget(repository);
                SvnPathTarget local = new SvnPathTarget(localPath);
                //client.GetInfo(declarationrRepository, out serverInfo);
                //client.GetInfo(local, out clientInfo);

                client.CleanUp(Path.GetDirectoryName(localPath));
                client.Revert(localPath);
                SvnUpdateArgs ua = new SvnUpdateArgs();
                SvnUpdateArgs svnUpdateArgs = new SvnUpdateArgs();
                svnUpdateArgs.Notify += delegate (object sender, SvnNotifyEventArgs e)
                {
                    if (filter(e))
                    {
                        files.Add(e.FullPath);
                    }
                    if (e.Action == SvnNotifyAction.UpdateCompleted)
                    {
                        import(files);

                    }
                };
                SvnUpdateResult result;
                client.Update(localPath, svnUpdateArgs, out result);

                //Console.WriteLine(string.Format("serverInfo revision of {0} is {1}", declarationrRepository, serverInfo.Revision));
                //Console.WriteLine(string.Format("clientInfo revision of {0} is {1}", local, clientInfo.Revision));
            }
        }

        [HttpPost]
        public ActionResult Upload(HttpFileCollectionBase files)
        {
            SyncSvn();
            StoreFile(f => GetService<DeclarationService>().Import(f));
            
            return RedirectToAction("Relation", "Order", new { ReturnUrl = ViewBag.ReturnUrl });
            // return RedirectToReturnUrl();
        }
    }
}